import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:example/image_dither_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_scaffold/flutter_scaffold.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

import '../generated/assets.dart';
import '../widget/template/template_edit_view.dart';
import '../widget/template/template_entity.dart';

class TemplateEditPage extends StatefulWidget {
  const TemplateEditPage({Key? key}) : super(key: key);

  @override
  State<TemplateEditPage> createState() => _TemplateEditPageState();
}

class _TemplateEditPageState extends State<TemplateEditPage> {
  late Template template;
  final GlobalKey<TemplateEditViewState> templateEditViewKey = GlobalKey();
  ui.Image? image;

  @override
  void initState() {
    super.initState();
    template = Template(
      id: 1,
      800,
      480,
      backgroundColor: 0xFF0000FF,
      enableColors: [0xFFFF0000, 0xFF000000, 0xFF00FF00],
      labels: [
        TemplateLabel(
          id: 1,
          x: 0,
          y: 20,
          width: 800,
          height: 80,
          textSize: 50,
          hintResId: 'title',
          textColor: 0xFFFF0000,
          textAlign: LabelTextAlign.center,
          labelType: LabelType.text,
        ),
        TemplateLabel(
          id: 2,
          x: 200,
          y: 0,
          width: 400,
          height: 400,
          textSize: 0,
          labelType: LabelType.image,
          imageUrl: Assets.imageImg1,
        ),
        TemplateLabel(
          id: 3,
          x: 50,
          y: 150,
          width: 80,
          height: 80,
          textSize: 0,
          textContent: 'QR Content',
          labelType: LabelType.qrcode,
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('TemplateEditView Demo')),
      body: Center(
        child: Container(
          decoration: BoxDecoration(
            border: BoxBorder.all(color: Colors.red, width: 1.w),
          ),
          child: LayoutBuilder(
            builder: (context, constraints) {
              final maxWidth = constraints.maxWidth; // 父容器可用最大宽度
              return TemplateEditView(
                key: templateEditViewKey,
                template: template,
                width: maxWidth,
                selectLineColor: Color(0xFF0072DB),
                onCheckedIndexChanged: (label) {
                  print('当前选中${label}');
                },
              );
            },
          ),
        ),
      ),
      floatingActionButton: Row(
        children: [
          FloatingActionButton(
            onPressed: () async {
              final picker = ImagePicker();
              final pickedFile = await picker.pickImage(
                source: ImageSource.gallery,
              );
              template.backgroundImage = pickedFile?.path;
              template.addLabel(
                TemplateLabel(
                  id: template.labels.length+1,
                  x: 100,
                  y: 100,
                  width: 200,
                  height: 200,
                  textSize: 0,
                  labelType: LabelType.image,
                  imageUrl: pickedFile?.path,
                ),
              );
            },
            child: image == null ? Icon(Icons.add) : RawImage(image: image),
          ),
          FloatingActionButton(
            heroTag: "btn2",
            onPressed: () async {
              final imageBytes = await templateEditViewKey.currentState
                  ?.captureToImage(width: 800, height: 480,);

              final stopwatch = Stopwatch()..start();
              var fixImage = await DitherImageUtil.rgbTripleDitherBytes(
                imageBytes!,
                800,
                480,
              );
              stopwatch.stop();
              print('耗时: ${stopwatch.elapsedMilliseconds} 毫秒');

              image = await rgbaToImage(fixImage, 800, 480);

              final byteData = await image?.toByteData(
                format: ui.ImageByteFormat.png,
              );

              final dir = await getApplicationSupportDirectory();
              final file = File('${dir.path}/template_capture.png');
              await file.writeAsBytes(byteData!.buffer.asUint8List());
              print("✅ 截图成功: ${file.path}");
              debugPrint(jsonEncode(template));
              setState(() {});
            },
            child: Icon(Icons.save),
          ),
          FloatingActionButton(
            heroTag: "btn3",
            onPressed: () async {
              template.backgroundColor = 0xFFFFFF00;
              setState(() {});
            },
            child: Icon(Icons.color_lens_sharp),
          ),
        ],
      ),
    );
  }

  Future<ui.Image> rgbaToImage(Uint8List rgba, int width, int height) async {
    final Completer<ui.Image> completer = Completer();
    ui.decodeImageFromPixels(
      rgba,
      width,
      height,
      ui.PixelFormat.rgba8888,
      (ui.Image img) => completer.complete(img),
    );
    return completer.future;
  }
}
